package com.ibest.card.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ibest.framework.common.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibest.framework.common.enums.EnumsRtnMapResult;
import com.ibest.framework.common.persistence.BaseController;
import com.ibest.utils.ConstantUtils;
import com.ibest.utils.RandomUtils;
import com.ibest.activity.entity.ActivityCard;
import com.ibest.activity.service.ActivityCardService;
import com.ibest.card.dto.input.CardInputDTO;
import com.ibest.card.entity.Card;
import com.ibest.card.service.CardService;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value="${adminPath}/card/card")
public class CardController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(CardController.class);
	
	@Autowired
	private CardService cardService;
	
	@Autowired
	private ActivityCardService activityService;
	
	/**
	* 进入到列表页
	*/
	@RequestMapping(value="/")
	public String index(){
		return "module/card/card/cardList";
	}
	
	/**
	* 进入到表单页-创建
	*/
	@RequestMapping(value="/add")
	public String add(){
		
		return "module/card/card/cardForm";
	}
	
	/**
	* 进入到表单页，编辑
	*/
	@RequestMapping(value="/edit")
	public String edit(@RequestParam String id, Model model){
		try {
			if(StringUtils.isNotEmpty(id)){
				Card card = cardService.findById(id);
				if(card != null){
					model.addAttribute("card", card);
				}else{
					setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "您查看的信息不存在！", model);
				}
			}else{
				setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "请选择需要编辑的信息！", model);
			}
		} catch (Exception e) {
			setRtnCodeAndMsg(EnumsRtnMapResult.EXCEPTION.getCode(), EnumsRtnMapResult.EXCEPTION.getMsg(), model);
		}
		return "module/card/card/cardForm";
	}
	
	/**
	* 进入到详情页
	*/
	@RequestMapping(value="/view")
	public String view(@RequestParam String id, Model model){
		try {
			if(StringUtils.isNotEmpty(id)){
				Card card = cardService.findById(id);
				if(card != null){
					model.addAttribute("card", card);
				}else{
					setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "您查看的信息不存在！", model);
				}
			}else{
				setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "请选择需要查看的信息！", model);
			}
		} catch (Exception e) {
			setRtnCodeAndMsg(EnumsRtnMapResult.EXCEPTION.getCode(), EnumsRtnMapResult.EXCEPTION.getMsg(), model);
		}
		return "module/card/card/cardDetail";
	}

	private static final String SCHEME_TYPE_HTTPS = "https";

	@ResponseBody
	@RequestMapping("/uploadImage")
	public RtnMap uploadImage(@RequestParam(value = "image") MultipartFile imageFile, HttpServletRequest request, Model model) {

		RtnMap rtnMap = new RtnMap();
		rtnMap.success("上传成功");

		if (imageFile != null) {
			//String destFile = FileUploadUtils.getDestFile(imageFile.getOriginalFilename(), null, request);

			try {
				// 保存文件
				//imageFile.transferTo(new File(request.getSession().getServletContext().getRealPath(File.separator) + destFile));
				// 生成网络地址
				//rtnMap.setRtnData(WebTools.getAppPath(request) + destFile.replaceAll("\\\\", "/"));
				String basepath = File.separator + "resources" + File.separator + "upload" + File.separator + "tmp";
				String path = FileUploadUtils.fileUpload(imageFile.getInputStream(), imageFile.getOriginalFilename(), basepath, request);
				if (com.ibest.framework.common.utils.StringUtils.isNotEmpty(path) && GlobalConfig.getSchemeType() == 1) {
					String subPath = path.substring(4);
					rtnMap.setRtnData(SCHEME_TYPE_HTTPS + subPath);
					model.addAttribute("imageUrl", subPath);
				} else {
					model.addAttribute("imageUrl", path);
					rtnMap.setRtnData(path);
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
				rtnMap.exception(e.getLocalizedMessage());
			} catch (IOException e) {
				e.printStackTrace();
				rtnMap.exception(e.getLocalizedMessage());
			} catch (Exception e) {
				e.printStackTrace();
				rtnMap.exception(e.getLocalizedMessage());
			}
		} else {
			rtnMap.failure("请上传文件");
		}

		return rtnMap;
	}

	/**
	* 异步分页查询
	*/
	@ResponseBody
	@RequiresPermissions("card:query")
	@RequestMapping(value="/list")
	public PageList<Card> list(CardInputDTO card, HttpServletRequest request){
		
		PageList<Card> pageList = new PageList<Card>();
		
		try {
			//设置分页参数
			super.setPage(request, pageList);
		
			pageList = cardService.findByPage(pageList, card);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pageList;
	}
	
	/**
	* 异步表单提交
	*/
	@ResponseBody
	@RequiresPermissions("card:create")
	@RequestMapping(value="create")
	public Map<String, Object> insert(Card card, HttpServletRequest request){

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "保存成功");
		
		String imageUrl = card.getImageUrl();
		try {
			// 将Base64图片数据保存成图片文件，修改对应的属性值
			if(StringUtils.isNotEmpty(imageUrl) && imageUrl.startsWith("data:image/")){
				String basepath = File.separator + "resources" + File.separator + "upload" + File.separator + "photo";
				String destFile = FileUploadUtils.base64ToFile(request, imageUrl, basepath);
				
				card.setImageUrl(WebTools.getAppPath(request) + destFile.replaceAll("\\\\", "/"));
			}
			Card unique = cardService.checkNameUnique(card.getName());
			if(unique!=null){
				setRtnCodeAndMsgByFailure(rtnMap, "保存失败,卡券名称已存在！");
			}else{
				card.setIsDelete(ConstantUtils.UPDATE_SET_ZERO);
				card.setState("0");
				card.setId(RandomUtils.RandomUUID());
				card.setCreater(UserUtils.getCurrentUser().getRealname());
				card.setCreateTime(new Date());
				card.setModifier(UserUtils.getCurrentUser().getRealname());
				card.setModifyTime(new Date());
				if (null == card.getNumTimeMax()) {
					card.setNumTimeMax(1);
				}
				if (null == card.getNumVinMax()) {
					card.setNumVinMax(1);
				}
				int result = cardService.insert(card);
				if(result == 0){
					setRtnCodeAndMsgByFailure(rtnMap, "保存失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}
	
	@ResponseBody
	@RequestMapping(value="updateState")
	public Map<String, Object> updateState(Card card){

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "修改成功！");
		
		try {
			String state=card.getState();
			if(!"0".equals(state)){
				List<ActivityCard> findByCardId = activityService.findByCardId(card.getId());
				if(findByCardId!=null && findByCardId.size()>0){
					setRtnCodeAndMsgByFailure(rtnMap, "修改失败！");
				}else{
					Card car = cardService.findById(card.getId());
					car.setState(state);
					int update = cardService.update(car);
					if(update == 0){
						setRtnCodeAndMsgByFailure(rtnMap, "修改失败！");
					}
				}
			}
			else{
				Card car = cardService.findById(card.getId());
				car.setState(state);
				int update = cardService.update(car);
				if(update == 0){
					setRtnCodeAndMsgByFailure(rtnMap, "修改失败！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}
	
	@ResponseBody
	@RequiresPermissions("card:update")
	@RequestMapping(value="update")
	public Map<String, Object> update(Card card, HttpServletRequest request){

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "保存成功");
		
		String imageUrl = card.getImageUrl();
		try {
			// 将Base64图片数据保存成图片文件，修改对应的属性值
			if(StringUtils.isNotEmpty(imageUrl) && imageUrl.startsWith("data:image/")){
				String basepath = File.separator + "resources" + File.separator + "upload" + File.separator + "photo";
				String destFile = FileUploadUtils.base64ToFile(request, imageUrl, basepath);
				
				card.setImageUrl(WebTools.getAppPath(request) + destFile.replaceAll("\\\\", "/"));
			}
			String oldName =
					cardService.findById(card.getId()).getName();
			if(!oldName.equals(card.getName())){
				Card unique = cardService.checkNameUnique(card.getName());
				if(unique!=null){
					setRtnCodeAndMsgByFailure(rtnMap, "保存失败,卡券名称已存在！");
				}else{
					card.setModifier(UserUtils.getCurrentUser().getRealname());
					card.setModifyTime(new Date());
					card.setState("1");
					int result = cardService.update(card);
					if(result == 0){
						setRtnCodeAndMsgByFailure(rtnMap, "保存失败");
					}
				}
			}else{
				card.setModifier(UserUtils.getCurrentUser().getRealname());
				card.setModifyTime(new Date());
				card.setState("1");
				int result = cardService.update(card);
				if(result == 0){
					setRtnCodeAndMsgByFailure(rtnMap, "保存失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}
	
	
	
	
	@ResponseBody
	@RequiresPermissions("card:delete")
	@RequestMapping(value="delete")
	public Map<String, Object> delete(@RequestParam(required=true) String ids){
		
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "删除成功");
		
		try {
			int result = cardService.deleteByIds(ids);
			if(result == 0){
				setRtnCodeAndMsgByFailure(rtnMap, "删除失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}

	/**
	 * 异步分页查询
	 */
	@ResponseBody
	@RequestMapping(value="/cards")
	public List<Card> cards(CardInputDTO inputDTO) throws Exception{
		return cardService.findByObject(inputDTO);
	}
}
